package com.ctshk.rpc.order.ship.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ctshk.common.dto.Result;
import com.ctshk.common.enums.IsDeletedCode;
import com.ctshk.common.enums.OrderCollectionStatus;
import com.ctshk.common.enums.SystemBusinessType;
import com.ctshk.common.enums.SystemError;
import com.ctshk.common.exception.BusinessException;
import com.ctshk.common.utils.EntityUtil;
import com.ctshk.rpc.finance.req.bill.BillOperateRefundReq;
import com.ctshk.rpc.finance.service.IFinanceBillService;
import com.ctshk.rpc.order.ship.dto.ShipOrderCollectionDTO;
import com.ctshk.rpc.order.ship.entity.ShipOrderCollection;
import com.ctshk.rpc.order.ship.mapper.ShipOrderCollectionMapper;
import com.ctshk.rpc.order.ship.req.ShipOrderCollectionReq2;
import com.ctshk.rpc.order.ship.service.IShipOrderCollectionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctshk.rpc.system.dto.UserDTO;
import com.ctshk.rpc.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 船票收款明细 服务实现类
 * </p>
 *
 * @author 刘蕾
 * @since 2021-03-16
 */
@Slf4j
@DubboService
public class ShipOrderCollectionServiceImpl extends ServiceImpl<ShipOrderCollectionMapper, ShipOrderCollection> implements IShipOrderCollectionService {


    @Autowired
    private ShipOrderCollectionMapper shipOrderCollectionMapper;
    @DubboReference
    private ISysUserService iSysUserService;
    @DubboReference
    private IFinanceBillService iFinanceBillService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result reconfirm(Long id, Long userId) {
        ShipOrderCollection shipOrderCollection = shipOrderCollectionMapper.selectById(id);
        if (shipOrderCollection == null) {
            //收款记录不存在
            throw new BusinessException(SystemError.SHIP_PRODUCT_11036);
        }
        if (shipOrderCollection.getStatus() == null || shipOrderCollection.getStatus() != OrderCollectionStatus.REJECT.getCode()) {
            // 收款记录的状态必须是驳回，才能再次确认
            throw new BusinessException(SystemError.SHIP_PRODUCT_11037);
        }
        shipOrderCollection.setStatus(OrderCollectionStatus.UN_REJECT.getCode());
        shipOrderCollection.setRejectInfo("");
        shipOrderCollection.setModifiedId(userId);
        shipOrderCollection.setGmtModified(LocalDateTime.now());
        shipOrderCollectionMapper.updateById(shipOrderCollection);

        //財務-再次確認
        if(StringUtils.isNotBlank(shipOrderCollection.getCollectionNumber())){
            BillOperateRefundReq billOperateRefundReq = new BillOperateRefundReq();
            billOperateRefundReq.setBillNumber(shipOrderCollection.getCollectionNumber());
            billOperateRefundReq.setBusinessType(SystemBusinessType.SHIP_TICKET.getCode());
            billOperateRefundReq.setUserId(userId);
            iFinanceBillService.reConfirm(billOperateRefundReq);
        }
        return Result.success();
    }

    @Override
    public Result<List<ShipOrderCollectionDTO>> list(ShipOrderCollectionReq2 shipOrderCollectionReq2) {
        QueryWrapper<ShipOrderCollection> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_deleted",0);
        queryWrapper.eq("order_id",shipOrderCollectionReq2.getOrderId());
        List<ShipOrderCollection> list = shipOrderCollectionMapper.selectList(queryWrapper);
        List<ShipOrderCollectionDTO> orderCollectionDTOS = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(list)){
            for(ShipOrderCollection scenicOrderCollection : list){
                ShipOrderCollectionDTO shipOrderCollectionDTO = EntityUtil.copy(scenicOrderCollection,ShipOrderCollectionDTO.class);
                UserDTO userDTO = null;
                try {
                    userDTO = iSysUserService.loadUserByParam(scenicOrderCollection.getSalerId(), 1);
                    shipOrderCollectionDTO.setSalerName(userDTO.getUsername() + "/" + userDTO.getDept());
                } catch (Exception e) {
                    throw new BusinessException(SystemError.SYS_502);
                }
                shipOrderCollectionDTO.setId(scenicOrderCollection.getId());
                shipOrderCollectionDTO.setCollectionAmount(scenicOrderCollection.getCollectionAmount());
                shipOrderCollectionDTO.setCurrency(scenicOrderCollection.getCurrency());
                orderCollectionDTOS.add(shipOrderCollectionDTO);
            }
        }
        return Result.success(orderCollectionDTOS);
    }

    @Override
    public Result rejectPayment(String collectionNumber, Long userId, String msg) {
        log.info("【船票订单收款-财务驳回收款】方法入参,number:{},msg:{},userId:{}", collectionNumber, msg, userId);
        ShipOrderCollection localFunOrderCollection = shipOrderCollectionMapper.selectOne(Wrappers.<ShipOrderCollection>lambdaQuery()
                .eq(ShipOrderCollection::getCollectionNumber, collectionNumber)
                .eq(ShipOrderCollection::getIsDeleted, IsDeletedCode.NO.getCode()));
        if (localFunOrderCollection == null) {
            //收款记录不存在
            return Result.failed(SystemError.SHIP_PRODUCT_11048);
        }
        if (localFunOrderCollection.getStatus() != null &&!Objects.equals(localFunOrderCollection.getStatus(), OrderCollectionStatus.REJECT.getCode())) {
            // 收款记录的状态必须不等于“已驳回”
            return Result.failed(SystemError.SHIP_PRODUCT_11034);
        }
        localFunOrderCollection.setStatus(OrderCollectionStatus.REJECT.getCode());
        localFunOrderCollection.setRejectInfo(msg);
        localFunOrderCollection.setModifiedId(userId);
        localFunOrderCollection.setGmtModified(LocalDateTime.now());
        shipOrderCollectionMapper.updateById(localFunOrderCollection);
        return Result.success();
    }
}
